from django.shortcuts import render_to_response
from django.utils.html import strip_tags
import json
from datetime import datetime, timedelta
from models import Tweet
from utils import get_handler

def sync(request, quiet=False):
    last_tweet = Tweet.objects.all()[0].twitter_id
    return sync_all(request, last_tweet, quiet=quiet)


def sync_all(request, since=False, quiet=False):
    if since:
        url = 'http://twitter.com/statuses/user_timeline.json?since_id=%d' % since
    else:
        url = 'http://twitter.com/statuses/user_timeline.json'
        
    response = get_handler().open(url)
    tweets = json.read(response.read())
    response.close()
    
    for tweet in tweets:
        t = Tweet()
        t.twitter_id = tweet['id']
        t.content = tweet['text']
        t.favorited = tweet['favorited']
        t.truncated = tweet['truncated']
        t.source = strip_tags(tweet['source'])
        
        # Manually correcting timezone! Take care of this in other localized apps!
        datetime_string = tweet['created_at'][4:20] + tweet['created_at'][26:30]
        t.created_at = datetime.strptime(datetime_string, '%b %d %H:%M:%S %Y') + timedelta(hours=2)
        
        t.save()
    
    if not quiet:
        return render_to_response('twitter/update.html', {'tweets': tweets})